package com.XZDP.controller;


import com.XZDP.dto.LoginFormDTO;
import com.XZDP.dto.Result;
import com.XZDP.dto.UserDTO;
import com.XZDP.entity.User;
import com.XZDP.entity.UserInfo;
import com.XZDP.service.IUserInfoService;
import com.XZDP.service.IUserService;
import com.XZDP.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.servlet.http.HttpSession;


@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private IUserInfoService userInfoService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 发送邮箱验证码
     */
    @PostMapping("/code")
    public Result sendCode(@RequestParam("phone") String phone, HttpSession session) throws MessagingException {
        log.info(phone);
        return userService.email(phone, session);
    }

    /**
     * 登录功能
     *
     * @param loginForm 登录参数，包含邮箱号、验证码；或者邮箱号、密码
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginFormDTO loginForm, HttpSession session) {
        log.info("用户邮箱:{},用户输入验证码:{}", loginForm.getPhone(), loginForm.getCode());
        return userService.EquCode(loginForm, session);
    }

    /**
     * 登出功能
     *
     * @return 无
     */
    @PostMapping("/logout")
    public Result logout(@RequestHeader("Authorization") String token) {
        UserHolder.removeUser();
        redisTemplate.delete("User:" + token);
        return Result.ok();
    }

    @GetMapping("/me")
    public Result me() {
        // 获取当前登录的用户并返回
        UserDTO user = UserHolder.getUser();
        return Result.ok(user);
    }

    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Long userId) {
        // 查询详情
        UserInfo info = userInfoService.getById(userId);
        if (info == null) {
            // 没有详情，应该是第一次查看详情
            return Result.ok();
        }
        info.setCreateTime(null);
        info.setUpdateTime(null);
        // 返回
        return Result.ok(info);
    }


    /**
     * ID查询用户信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result getByUserId(@PathVariable("id") Long id) {
        User byId = userService.getById(id);
        return Result.ok(byId);
    }


    /**
     * 用户签到
     * @return
     */
    @PostMapping("/sign")
    public Result sign() {
        return userService.sign();
    }

    /**
     * 用户连续签到
     * @return
     */
    @GetMapping("/sign/count")
    public Result countSign() {
        return userService.countSign();
    }
}
